// import Vue from 'vue';
import apiConfig from "./apiConfig";
// import { urlParams } from "@utils/UtilsFunc";
import _randkey from "@/utils/randkey";
import uuid from "uuid-random";
import Validater from "@/utils/Validater";
import { customizedPush } from "@/router/history";
import _R from "./fetchConfig/fetch_util";
import { Toast } from 'vant';
// Vue.use(Toast);

const env = process.env.VUE_APP_ENV;
// const routeName = process.env.REACT_APP_ROUTE_NAME;
console.log("eeeeenv",env);
let currentHost = `${apiConfig.HOST[env]}`;
currentHost = "DEV";
// currentHost = "MOCK";

currentHost =
  process.env.NODE_ENV === "production"
    ? `${apiConfig.HOST[env]}`
    : currentHost;

const commonPromiseHandler = (uri, params, isFormData) => {
  return new Promise((resolve, reject) => {
    _R[`${isFormData ? "customizedFetch" : "fetch"}`](uri, params)
      .then((res) => {
        if (Validater.isResponseValid(res)) {
          resolve(res); //外面请求.then
        } else if (!Validater.isTokenValid(res)) {
          // Toast.hide();
          console.log("res.header.retMsg", res.header.retMsg);
          Toast.fail(res.header.retMsg);
          // Toast.fail("登陆过期，请重新登陆");
          localStorage.removeItem("rz_token");
          customizedPush({
            pathname: "LoginPage"
          });
          reject(res);
        } else {
          Toast.hide();
          const {
            header: { retMsg } = {
              retMsg: "报文返回体错误！"
            }
          } = res;
          // console.log("retMsg", retMsg);
          Toast.fail(retMsg);
          reject(res);
        }
      })
      .catch((e) => {
        reject(e);
        console.log("失败 e", e);
      });
  });
};

const getCommonHeader = () => {
  const timestamp = Math.round(new Date().getTime()) + "";
  return {
    openId: localStorage.getItem("photovoltaics_openId") || "1.0",
    timestamp: timestamp,
    reqNo: uuid(),
    token: localStorage.getItem("rz_token")
      ? localStorage.getItem("rz_token")
      : "0",
    sign: ""
  };
};

const api = {
  createWxUser(
    openId,
    nickName,
    gender,
    city,
    province,
    country,
    headImgUrl,
    appId
  ) {
    return commonPromiseHandler(
      `${currentHost}/${apiConfig.URI.CREATE_WX_USER}`,
      {
        openId: openId,
        nickName: nickName,
        gender: gender,
        city: city,
        province: province,
        country: country,
        headImgUrl: headImgUrl,
        appId: appId
      }
    );
  },
  sendSMSCode(phone) {
    const commonHeader = getCommonHeader();

    return commonPromiseHandler(
      `${currentHost}/${apiConfig.URI.SEND_SMS_CODE}`,
      {
        data: {
          mobileNo: "13433019016",
          scene: "REGISTER_OR_LOGIN"
        },
        header: commonHeader
      }
    );
  },

 


 

};

export default api;
